import type { ApiResponse } from './type'
import { createAlova } from 'alova'
import VueHook from 'alova/vue'
import { onAuthRequired, onResponseRefreshToken } from './auth'
import { mockAdapter } from './mock'

const alovaInstance = createAlova({
  baseURL: import.meta.env.VITE_GLOB_API_URL + import.meta.env.VITE_GLOB_API_URL_PREFIX,
  statesHook: VueHook,
  cacheFor: null,
  timeout: 10000,
  beforeRequest: onAuthRequired(),
  requestAdapter: mockAdapter,
  responded: onResponseRefreshToken(async (response) => {
    if (response.status !== 200) {
      return Promise.reject(response.statusText)
    }
    const data = await response.clone().json() as ApiResponse
    return data.data
  }),
})

export { alovaInstance }
